"""
Copyright (c) 2023 - present SKbioinfo
"""
import base64
import re,os
from datetime import datetime
from flask_restful import Resource
from flask import request,jsonify,current_app
from apps.API.utils.log_helper import lg
from flask_jwt_extended import jwt_required
'''URL:/api/signature/UploadSignatrue/<string:id>'''
class interfaceUploadSignature(Resource):
    def _decode_base64(self,data):
        """
        自动补全Base64字符串的padding并解码
        """
        # 计算需要补足的等号数量
        if len(data) % 4 !=0:
            num_padding = 4 - len(data) % 4
            data += '=' * num_padding
        return base64.b64decode(data)
    
    @jwt_required()
    def post(self,id):
        try:
            image_data = request.get_json("image")["image"]
            if not image_data.startswith('data:image'):
                return jsonify({'error': 'Invalid image format'}), 400
            header,encoded = image_data.split(',',1)
            file_type = re.findall(r'data:image/(\w+);base64', header)
            if not file_type:
                return jsonify({'error': 'Invalid image header'}), 400
            file_type = file_type[0].lower()
            image_bytes = self._decode_base64(encoded)
            timestamp = datetime.now().strftime('%Y%m%d_%H%M%S_%f')
            filename = f"{id}_sig_{timestamp}.{file_type}"
            baseDir=current_app.config.get("BASE_DIR")
            filepath = os.path.join(f"{baseDir}", filename)
            with open(filepath, 'wb') as f:
                f.write(image_bytes)
            response=jsonify({})
            response.status=202
            return response
        except Exception as e:
            lg.error(e)
            return 404    
